#include "orderlistwidget.h"
#include "errorhandler.h"
#include <QDateTime>

OrderListWidget::OrderListWidget(QWidget *parent)
    : QWidget(parent)
    , m_layout(nullptr)
    , m_tableWidget(nullptr)
    , m_selectedOrderId("")
    , m_isUpdating(false)
{
    setupTable();
}

OrderListWidget::~OrderListWidget()
{
    // Qt会自动清理子对象
}

void OrderListWidget::setOrders(const QList<Order>& orders)
{
    m_isUpdating = true;
    m_orders = orders;
    populateTable();
    m_isUpdating = false;
}

void OrderListWidget::addOrder(const Order& order)
{
    if (!order.isValid()) {
        return;
    }
    
    m_isUpdating = true;
    
    // 检查是否已存在
    int existingRow = findRowByOrderId(order.id);
    if (existingRow >= 0) {
        // 已存在，更新数据
        updateRowData(existingRow, order);
    } else {
        // 新增订单
        m_orders.append(order);
        
        int newRow = m_tableWidget->rowCount();
        m_tableWidget->insertRow(newRow);
        updateRowData(newRow, order);
    }
    
    m_isUpdating = false;
}

void OrderListWidget::updateOrder(const Order& order)
{
    if (!order.isValid()) {
        return;
    }
    
    m_isUpdating = true;
    
    // 查找并更新
    int row = findRowByOrderId(order.id);
    if (row >= 0) {
        // 更新内存中的数据
        for (int i = 0; i < m_orders.size(); ++i) {
            if (m_orders[i].id == order.id) {
                m_orders[i] = order;
                break;
            }
        }
        
        // 更新表格显示
        updateRowData(row, order);
    }
    
    m_isUpdating = false;
}

void OrderListWidget::removeOrder(const QString& orderId)
{
    if (orderId.isEmpty()) {
        return;
    }
    
    m_isUpdating = true;
    
    int row = findRowByOrderId(orderId);
    if (row >= 0) {
        m_tableWidget->removeRow(row);
        
        // 从内存中移除
        for (int i = 0; i < m_orders.size(); ++i) {
            if (m_orders[i].id == orderId) {
                m_orders.removeAt(i);
                break;
            }
        }
        
        // 如果是当前选中的订单，清空选择
        if (m_selectedOrderId == orderId) {
            m_selectedOrderId.clear();
        }
    }
    
    m_isUpdating = false;
}

void OrderListWidget::clearSelection()
{
    m_tableWidget->clearSelection();
    m_selectedOrderId.clear();
}

QString OrderListWidget::getCurrentSelectedOrderId() const
{
    return m_selectedOrderId;
}

void OrderListWidget::onSelectionChanged()
{
    if (m_isUpdating) {
        return;
    }
    
    int currentRow = m_tableWidget->currentRow();
    if (currentRow >= 0 && currentRow < m_tableWidget->rowCount()) {
        QTableWidgetItem* orderIdItem = m_tableWidget->item(currentRow, COL_ORDER_ID);
        if (orderIdItem) {
            QString orderId = orderIdItem->text();
            if (orderId != m_selectedOrderId) {
                m_selectedOrderId = orderId;
                emit orderSelected(orderId);
            }
        }
    } else {
        if (!m_selectedOrderId.isEmpty()) {
            m_selectedOrderId.clear();
            emit orderSelected("");
        }
    }
}

void OrderListWidget::onItemDoubleClicked(QTableWidgetItem* item)
{
    if (!item) {
        return;
    }
    
    int row = item->row();
    QTableWidgetItem* orderIdItem = m_tableWidget->item(row, COL_ORDER_ID);
    if (orderIdItem) {
        QString orderId = orderIdItem->text();
        emit orderDoubleClicked(orderId);
    }
}

void OrderListWidget::setupTable()
{
    // 创建布局
    m_layout = new QVBoxLayout(this);
    m_layout->setContentsMargins(0, 0, 0, 0);
    m_layout->setSpacing(0);
    
    // 创建表格
    m_tableWidget = new QTableWidget(this);
    m_layout->addWidget(m_tableWidget);
    
    // 设置表格属性
    m_tableWidget->setColumnCount(COL_COUNT);
    m_tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    m_tableWidget->setAlternatingRowColors(true);
    m_tableWidget->setSortingEnabled(true);
    m_tableWidget->setShowGrid(true);
    m_tableWidget->setGridStyle(Qt::SolidLine);
    
    // 设置表格头部
    setupHeaders();
    
    // 连接信号
    connect(m_tableWidget, &QTableWidget::itemSelectionChanged,
            this, &OrderListWidget::onSelectionChanged);
    connect(m_tableWidget, &QTableWidget::itemDoubleClicked,
            this, &OrderListWidget::onItemDoubleClicked);
    
    // 设置样式
    m_tableWidget->setStyleSheet(R"(
        QTableWidget {
            background-color: white;
            border: 1px solid #D0D0D0;
            font-size: 11px;
            gridline-color: #E0E0E0;
        }
        
        QTableWidget::item {
            padding: 4px;
            border-bottom: 1px solid #E0E0E0;
        }
        
        QTableWidget::item:selected {
            background-color: #E3F2FD;
            color: black;
        }
        
        QTableWidget::item:hover {
            background-color: #F5F5F5;
        }
        
        QHeaderView::section {
            background-color: #F0F0F0;
            border: 1px solid #D0D0D0;
            font-weight: bold;
            padding: 6px;
            font-size: 11px;
        }
    )");
}

void OrderListWidget::setupHeaders()
{
    QStringList headers;
    headers << "订单号" << "顾客" << "状态" << "金额" << "创建时间";
    m_tableWidget->setHorizontalHeaderLabels(headers);
    
    // 设置列宽 (总宽度约420px，适合500px的容器)
    QHeaderView* header = m_tableWidget->horizontalHeader();
    header->resizeSection(COL_ORDER_ID, 120);    // 订单号
    header->resizeSection(COL_CUSTOMER, 80);     // 顾客
    header->resizeSection(COL_STATUS, 70);       // 状态
    header->resizeSection(COL_AMOUNT, 80);       // 金额
    header->resizeSection(COL_CREATE_TIME, 90);  // 创建时间
    
    // 设置最后一列自动伸缩
    header->setStretchLastSection(true);
    
    // 设置行高
    m_tableWidget->verticalHeader()->setDefaultSectionSize(28);
    m_tableWidget->verticalHeader()->setVisible(false);
}

void OrderListWidget::populateTable()
{
    // 清空现有数据
    m_tableWidget->setRowCount(0);
    
    // 添加所有订单
    for (int i = 0; i < m_orders.size(); ++i) {
        m_tableWidget->insertRow(i);
        updateRowData(i, m_orders[i]);
    }
    
    // 排序（默认按创建时间降序）
    m_tableWidget->sortItems(COL_CREATE_TIME, Qt::DescendingOrder);
}

void OrderListWidget::updateRowData(int row, const Order& order)
{
    if (row < 0 || row >= m_tableWidget->rowCount()) {
        return;
    }
    
    // 订单号
    QTableWidgetItem* orderIdItem = new QTableWidgetItem(order.id);
    orderIdItem->setFlags(orderIdItem->flags() & ~Qt::ItemIsEditable);
    m_tableWidget->setItem(row, COL_ORDER_ID, orderIdItem);
    
    // 顾客 (通过顾客ID查询用户名)
    QString customerName = getCustomerName(order.customerId);
    QTableWidgetItem* customerItem = new QTableWidgetItem(customerName);
    customerItem->setFlags(customerItem->flags() & ~Qt::ItemIsEditable);
    customerItem->setToolTip(QString("顾客ID: %1").arg(order.customerId)); // 添加工具提示显示顾客ID
    m_tableWidget->setItem(row, COL_CUSTOMER, customerItem);
    
    // 状态
    QString statusText = getStatusDisplayText(order.status);
    QString statusColor = getStatusColor(order.status);
    QTableWidgetItem* statusItem = new QTableWidgetItem(statusText);
    statusItem->setFlags(statusItem->flags() & ~Qt::ItemIsEditable);
    statusItem->setForeground(QColor(statusColor));
    if (order.status == OrderStatus::PREPARING) {
        statusItem->setFont(QFont("Microsoft YaHei", 11, QFont::Bold));
    }
    m_tableWidget->setItem(row, COL_STATUS, statusItem);
    
    // 金额
    QString amountText = formatAmount(order.totalAmount);
    QTableWidgetItem* amountItem = new QTableWidgetItem(amountText);
    amountItem->setFlags(amountItem->flags() & ~Qt::ItemIsEditable);
    amountItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
    m_tableWidget->setItem(row, COL_AMOUNT, amountItem);
    
    // 创建时间
    QString timeText = formatTime(order.createdDate);
    QTableWidgetItem* timeItem = new QTableWidgetItem(timeText);
    timeItem->setFlags(timeItem->flags() & ~Qt::ItemIsEditable);
    timeItem->setData(Qt::UserRole, order.createdDate); // 存储原始时间用于排序
    m_tableWidget->setItem(row, COL_CREATE_TIME, timeItem);
    

}

int OrderListWidget::findRowByOrderId(const QString& orderId)
{
    for (int row = 0; row < m_tableWidget->rowCount(); ++row) {
        QTableWidgetItem* item = m_tableWidget->item(row, COL_ORDER_ID);
        if (item && item->text() == orderId) {
            return row;
        }
    }
    return -1;
}

QString OrderListWidget::getStatusDisplayText(OrderStatus status) const
{
    switch (status) {
        case OrderStatus::PENDING: return "待处理";
        case OrderStatus::PREPARING: return "制作中";
        case OrderStatus::COMPLETED: return "已完成";
        case OrderStatus::CANCELLED: return "已取消";
        default: return "未知";
    }
}

QString OrderListWidget::getStatusColor(OrderStatus status) const
{
    switch (status) {
        case OrderStatus::PENDING: return "#FF9800";    // 橙色
        case OrderStatus::PREPARING: return "#2196F3";  // 蓝色
        case OrderStatus::COMPLETED: return "#4CAF50";  // 绿色
        case OrderStatus::CANCELLED: return "#F44336";  // 红色
        default: return "#666666";                       // 灰色
    }
}

QString OrderListWidget::formatAmount(double amount) const
{
    return QString("¥%1").arg(amount, 0, 'f', 2);
}

QString OrderListWidget::formatTime(const QDateTime& dateTime) const
{
    if (!dateTime.isValid()) {
        return "-";
    }
    
    QDate today = QDate::currentDate();
    QDate orderDate = dateTime.date();
    
    if (orderDate == today) {
        // 今天的订单只显示时间
        return dateTime.toString("hh:mm");
    } else if (orderDate == today.addDays(-1)) {
        // 昨天的订单
        return "昨天 " + dateTime.toString("hh:mm");
    } else {
        // 其他日期
        return dateTime.toString("MM-dd hh:mm");
    }
}

QString OrderListWidget::getCustomerName(const QString& customerId) const
{
    try {
        // 通过DataManager获取顾客信息
        Customer customer = DataManager::instance().getCustomerById(customerId);
        if (customer.isValid() && !customer.username.isEmpty()) {
            return customer.username;
        }
    } catch (const std::exception& e) {
        // 如果查询失败，记录错误但不影响显示
        LOG_WARNING(QString("Failed to get customer name for ID %1: %2").arg(customerId).arg(e.what()), 
                   "OrderListWidget::getCustomerName");
    }
    
    // 如果无法获取用户名，返回格式化的顾客ID
    return QString("顾客 %1").arg(customerId);
}
